<template>
  <a-row>
    <a-card :body-style="{padding: '24px 32px'}" :bordered="false" :span="8">
      <a-col :span="5">
        <a-dropdown :trigger="['click']" placement="bottomCenter" style="margin-left: 10px">
          <a-menu slot="overlay">
            <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
            <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
            <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
            <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
          </a-menu>
          <a-button>
            树操作
            <a-icon type="down"/>
          </a-button>
        </a-dropdown>
        <a-alert type="info" showIcon style="margin-top: 5px">
          <div slot="message">
            <span>当前选择：{{ (checkDeptName||'') }} </span>
            <a style="margin-left: 10px;" @click="onClearSelected" v-if="checkDeptName">取消选择</a>
          </div>
        </a-alert>
        <a-input-search style="margin-bottom: 8px;margin-top: 5px" placeholder="请输入部门" @change="onChange"/>
        <template>
          <div>
            <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
              <span style="user-select: none">
                <a-tree
                        v-if="departTree.length"
                        checkable
                        checkStrictly
                        @check="onCheck"
                        @expand="onExpand"
                        @rightClick="rightHandle"
                        :defaultExpandedKeys="defaultExpandedKeys"
                        :expandedKeys="expandedKeys"
                        :autoExpandParent="autoExpandParent"
                        v-model="checkedKeys"
                        @select="onSelect"
                        :selectedKeys="selectedKeys"
                        :treeData="departTree"
                /></span>
              <a-menu slot="overlay">
                <a-menu-item @click="handleAdd" key="1">添加</a-menu-item>
                <a-menu-item @click="handleDelete" key="2" >删除</a-menu-item>
                <a-menu-item @click="closeDrop" key="3">取消</a-menu-item>
              </a-menu>
            </a-dropdown>
          </div>
        </template>

      </a-col>
      <a-col :span="19">
        <a-form-model
                ref="ruleForm"
                :model="selectDeptInfo"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
        >
          <a-form-model-item
                  label="分类名称"
                  prop="name"
                  ref="name"
                  :rules="$valid.required"
                  :maxLength="50">
            <a-input v-model="selectDeptInfo.name" placeholder="请输入"/>
          </a-form-model-item>

          <a-form-model-item
                  label="上级分类"
                  prop="parentId"
                  >
            <a-input v-model="selectDeptInfo.parentId" placeholder="请输入" type="hidden"/>
            <a-input-search
                    placeholder="点击右侧按钮选择部门"
                    v-model="selectDeptInfo.parentName"
                    onfocus="this.blur()"
                    @search="departCodeSearch">
            </a-input-search>
          </a-form-model-item>
          <a-form-model-item
                  label="排序"
                  prop="sortOrder"
                  ref="sortOrder"
                  :rules="$valid.numRules">
            <a-input-number :min="1" v-model="selectDeptInfo.sortOrder" placeholder="请输入"/>
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button
                    type="primary"
                    @click="onSubmit"
                    v-if="orgCategoryDisabled"
                    >
              修改并保存
            </a-button>
            <a-button
                    type="primary"
                    @click="onSubmit"
                    v-if="!orgCategoryDisabled"
                   >
              新增
            </a-button>
            <a-button style="margin-left: 10px;" @click="resetForm" >
              重置
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </a-col>
    </a-card>
  </a-row>
</template>

<script>
  import { STable, Ellipsis } from '@/components'
  import { deleteAction, postAction,getAction } from '@/api/manage'
  import { mixin } from '@/utils/mixin'
  import EquTypeEdit from './EquTypeEdit'
  import EquTypeView from './EquTypeView'
  let expandedKeySource = []
  let selectList = []
  let selectParentList = []
  export default {
    name: 'EquTypeList',
    mixins: [mixin],
    components: { STable, Ellipsis, EquTypeEdit, EquTypeView },
    data () {
      return {
        visible: false,
        // 查询条件
        queryParam: {
          title: ''
        },
        // 表头
        // 如果需要字典，那么需要在columns列中加入 customRender: (text) => this.$sysDictFilter(text, 'xxxx')xxxx 为dataIndex
          labelCol: { span: 4 },
          wrapperCol: { span: 14 },
          defaultExpandedKeys: [],
          expandedKeys: [],
          autoExpandParent: true,
          checkedKeys: [],
          selectedKeys: [],
          rightClickSelectedKey: '',
          rightClickSelectedValue: '',
          rightClickSelectedName: '',
          allTreeKeys: [],
          dropTrigger: '11',
          orgCategoryDisabled: false,
          selectDeptInfo: {
              parentId: undefined,
              parentName: undefined,
              areaCode: undefined,
              areaData: undefined,
              address: undefined,
              orgFlag: 0
          },
          checkDeptName: '',
          departTree: [],
          departListSys: [],
        url: {
          treelist: '/system/equType/tree',
          delete: '/system/equType/delete',
            saveInfo:'/system/equType/save',
            getInfo: '/system/equType/info'
        }
      }
    },
      created () {
          this.initData(true)
      },
    computed: {},
      watch: {
          selectedKeys (val) {
              this.$refs.ruleForm.resetFields()
          }
      },
    methods: {
        initData (firstFlag) {
            getAction(this.url.treelist,{}).then(res => {
                if (firstFlag) {
                    if(res.result.data[0].children) {
                        const treeLv2 = res.result.data[0].children.map((item, index, arr) => {
                            const treeLv2Tmp = (item.key)
                            return treeLv2Tmp
                        })
                        this.expandedKeys = treeLv2
                        expandedKeySource = treeLv2
                    }
                }
                console.log("depart:",res)
                this.departTree = res.result.data
                this.getAllKeys(this.departTree)
            })
        },
        onSubmit () {
            this.$refs.ruleForm.validate(valid => {
                console.log(valid)
                if (valid) {
                    postAction(this.url.saveInfo,this.selectDeptInfo).then(res => {
                        this.checkDeptName = this.selectDeptInfo.name
                        this.$message.success(res.content)
                        this.initData(false)
                        this.resetForm()
                    })
                } else {
                    return false
                }
            })
        },
        // 右键点击下拉框改变事件
        dropStatus (visible) {
            if (visible === false) {
                this.dropTrigger = ''
            }
        },
        // 展开所有
        expandAll () {
            this.expandedKeys = this.allTreeKeys
        },
        // 关闭所有
        closeAll () {
            this.expandedKeys = []
        },
        // 全选
        checkALL () {
            this.checkedKeys = this.allTreeKeys
        },
        // 取消全选
        cancelCheckALL () {
            this.checkedKeys = []
        },
        // 添加
        handleAdd () {
            this.selectDeptInfo.parentId = undefined
            this.selectDeptInfo.parentName = ''
            this.orgCategoryDisabled = false
            this.selectDeptInfo.id = undefined
            this.checkDeptName = ''
            this.$refs.ruleForm.resetFields()
            this.selectDeptInfo.parentId = this.rightClickSelectedValue
            this.selectDeptInfo.parentName = this.rightClickSelectedName
            this.selectDeptInfo.address = ''
        },

        // 右键店家下拉关闭下拉框
        closeDrop () {
            this.dropTrigger = ''
        },
        // 右键操作方法
        rightHandle (node) {
            this.dropTrigger = 'contextmenu'
            this.rightClickSelectedKey = node.node.eventKey
            this.rightClickSelectedValue = node.node.value
            this.rightClickSelectedName = node.node.title
        },
        // 获取所有的key
        getAllKeys (node) {
            node.map((item, index, arr) => {
                this.allTreeKeys.push(item.key)
                const node = {}
                node.id = item.id
                node.key = item.key
                node.title = item.title
                node.parentId = item.parentId
                this.departListSys.push(node)
                if (item.children && item.children.length > 0) {
                    this.getAllKeys(item.children)
                }
            })
        },
        // 右键点击下拉框改变事件
        dropStatus (visible) {
            if (visible === false) {
                this.dropTrigger = ''
            }
        },
        // 获取用户对应部门弹出框提交给返回的数据
        departCodeOk (formData) {
            const departCodeNames = []
            const departCodeKeys = []
            let departCodeNameString = ''
            for (let i = 0; i < formData.departIdList.length; i++) {
                departCodeKeys.push(formData.departIdList[i].key)
                departCodeNames.push(formData.departIdList[i].title)
                departCodeNameString = departCodeNames.join(',')
            }
            if (departCodeKeys.length > 0) {
                this.selectDeptInfo.parentId = departCodeKeys[0]
                this.selectDeptInfo.parentName = departCodeNameString
            }
        },
        // 搜索用户对应的归属部门API
        departCodeSearch () {
            this.$refs.departCodeRef.add([this.selectDeptInfo.parentId])
        },
        // 重置表单
        resetForm () {
            this.selectDeptInfo.parentId = undefined
            this.selectDeptInfo.parentName = ''
            this.orgCategoryDisabled = false
            this.selectDeptInfo.id = undefined
            this.selectDeptInfo.areaCode = undefined
            this.selectDeptInfo.areaData = undefined
            this.checkDeptName = ''
            this.selectedKeys = []
            this.selectDeptInfo.address = ''
            this.$refs.ruleForm.resetFields()
        },

        handleIconChange (icon) {
            console.log('change Icon', icon)
        },
        // tree 展开
        onExpand (expandedK, expandedExtr) {
            this.expandedKeys = expandedK
        },
        // 清空选择
        onClearSelected () {
            this.resetForm()
        },
        // 触发onSelect事件时,为部门树右侧的form表单赋值
        setValuesToForm (record) {
            this.orgCategoryDisabled = true
            getAction(this.url.getInfo,{ id: record.id }).then(res => {
                const data = res.result.data
                this.selectDeptInfo = data
            })
        },
        // 触发选中事件 勾选复选框
        onCheck (checkedKeys, info) {
            console.log('onCheck', checkedKeys, info)
            this.hiding = false
            // this.checkedKeys = checkedKeys.checked
            if (this.checkStrictly) {
                this.checkedKeys = checkedKeys.checked
            } else {
                this.checkedKeys = checkedKeys
            }
        },
        // 触发点击事件
        onSelect (selectedKeys, info) {
            this.$refs.ruleForm.resetFields()
            this.selectedKeys = selectedKeys
            const record = info.node.dataRef
            this.setValuesToForm(record)
            this.checkDeptName = record.title
        },
        // 编辑情况下，禁止选择当前节点及其子节点
        diGuiTreeEdit (item, vals) {
            const data = item
            const treeAry = []
            for (const i in data) {
                const v = data[i]
                const node = {}
                if (v === null || v === undefined) {
                } else {
                    if (v.children && v.children.length > 0) {
                        if (v.title.indexOf(vals) > -1) {
                            node.class = 'k-tree-select'
                            selectList.push(v.parentId)
                        } else {
                            node.class = ''
                        }
                        node.key = v.key
                        node.title = v.title
                        node.parentId = v.parentId
                        node.children = this.diGuiTreeEdit(v.children, vals)
                        treeAry.push(node)
                    } else {
                        if (v.title.indexOf(vals) > -1) {
                            node.class = 'k-tree-select'
                            selectList.push(v.parentId)
                        } else {
                            node.class = ''
                        }
                        node.key = v.key
                        node.title = v.title
                        node.parentId = v.parentId
                        treeAry.push(node)
                    }
                }
            }
            return treeAry
        },
        // 获取父节点
        getParents (checkKey) {
            for (var i = 0; i < this.departListSys.length; i++) {
                const tmp = this.departListSys[i]
                if (tmp.id === parseInt(checkKey)) {
                    selectParentList.push(tmp.key)
                    if (this.checkHasParent(tmp.parentId)) {
                        this.getParents(tmp.parentId)
                    }
                }
            }
        },
        // 检查是否有父节点
        checkHasParent (checkKey) {
            for (var i = 0; i < this.departListSys.length; i++) {
                const tmp = this.departListSys[i]
                if (tmp.id === checkKey) {
                    return tmp.id
                }
            }
        },
        // 左侧检索
        onChange (e) {
            let value = e.target.value
            if (!value) {
                value = '@@@@'
            }
            selectList = []
            selectParentList = []
            this.departTree = this.diGuiTreeEdit(this.departTree, value)
            this.expandedKeys = []
            selectList.map(x => {
                this.getParents(x)
                selectParentList.map(x => {
                    this.expandedKeys.push(x)
                })
            })
            if (this.expandedKeys.length === 0) {
                this.expandedKeys = expandedKeySource
            }
        },
      // 删除
      handleDelete () {
        deleteAction(this.url.delete, { ids: this.rightClickSelectedValue }).then((resp) => {
            this.$message.success('删除成功!')
            this.initData(false)
        })
      },
      // 用户编辑
      handleEdit (record) {
        this.$refs.modalEdit.edit(record)
      },
      searchQuery () {
        this.$refs.table.refresh(true)
      },
      // 保存刷新
      modalEditOk () {
        this.$refs.table.refresh()
      },
      // 查看
      handelView (record) {
        this.$refs.modalView.show(record)
      },
      //开启选择
      onSelectChange (selectedRowKeys) {
         console.log('selectedRowKeys changed: ', selectedRowKeys)
         this.selectedRowKeys = selectedRowKeys
      },
    },
    watch: {}
  }
</script>
<style scoped>
</style>
